package com.hc.demo.service;

import com.hc.demo.domain.Hospital;
import com.hc.demo.domain.Orders;
import com.hc.demo.domain.Setmeal;
import com.hc.demo.dto.ResultResponse;
import com.hc.demo.exception.TijianException;
import com.hc.demo.exception.TijianExceptionEnum;
import com.hc.demo.mapper.HospitalMapper;
import com.hc.demo.mapper.OrdersMapper;
import com.hc.demo.mapper.SetmealMapper;
import com.hc.demo.utils.SendMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    HospitalMapper hospitalMapper;
    @Autowired
    SetmealMapper setmealMapper;
    @Autowired
    SendMessage sendMessage;

    /**
     * 创建订单的方法
     */
    @Override
    @Transactional  //开启事务的注解，确保整个操作符合事务的四个特征：原子性 一致性  持久性 隔离性
    public ResultResponse createOrders(Orders orders){
        ResultResponse resultResponse=null;
        /*
        算法：
        1.检查该用户当天有没有重复预约  Orders表与当前用户有关的数据锁住  select * from orders where userId=? and orderDate=?
        2.检查医院有没有余号   获取医院的当天的总号数-已经预约的号数=余号数量
        3.调用Mapper往数据库插入一条订单数据
         */
        List<Orders> ordersList=ordersMapper.selectByUserIdAndOrderDate(orders);
        System.out.println("ordersList：");
        if(ordersList!=null&&ordersList.size()>0){
            throw new TijianException(TijianExceptionEnum.ALREADY_APPOINTMENT.getEnCode(),TijianExceptionEnum.ALREADY_APPOINTMENT.getEnMessage());
        }
        //2.检查医院有没有余号   获取医院的当天的总号数-已经预约的号数=余号数量
        if(!haveRemainderNumber(orders)){
            throw new TijianException(TijianExceptionEnum.NOT_HAVE_REMAINDER_NUMBER.getEnCode(),TijianExceptionEnum.NOT_HAVE_REMAINDER_NUMBER.getEnMessage());
        }

        //往数据库插入一条订单数据
        ordersMapper.insertOrder(orders);
        resultResponse=new ResultResponse(ResultResponse.SUCCESS_CODE,ResultResponse.SUCCESS_DESC);
        return resultResponse;
    }

    @Override
    public ResultResponse queryOrderByUserId(String userId) {
        System.out.println("JVM默认时区: " + TimeZone.getDefault().getID());
        System.out.println("当前时间: " + new Date());
       //1.查询用户的订单
        List<Orders> ordersList=ordersMapper.selectByUserId(userId);

        //2.这个for循环帮助每个订单 获取  对应套餐数据
        for(Orders o:ordersList){
            System.out.println("orderDate:"+o.getOrderDate());
            Integer smId=o.getSmId();

            //那种套餐编号去查询套餐表，这样就能获取套餐信息
           Setmeal setmeal=setmealMapper.selectByPrimaryKey(smId);

            o.setSetmeal(setmeal);

        }

        return new ResultResponse(ResultResponse.SUCCESS_CODE,ResultResponse.SUCCESS_DESC,ordersList);
    }

    @Override
    public ResultResponse queryOrderByUserIdAndState(Orders orders) {
//        System.out.println("JVM默认时区: " + TimeZone.getDefault().getID());
//        System.out.println("当前时间: " + new Date());
        //1.查询用户的所有订单
        List<Orders> ordersList=ordersMapper.selectByUserIdAndState(orders);

        //2.这个for循环帮助每个订单 获取  对应套餐数据
        for(Orders o:ordersList){


                //我们发现这个订单集合中，订单数据中没有医院名称，所以我们需要再查询一下医院数据，然后放入order对象中保存起来
                Integer hpId=o.getHpId();
               Hospital hospital=hospitalMapper.selectByPrimaryKey(hpId);
               o.setHospital(hospital);


        }

        return new ResultResponse(ResultResponse.SUCCESS_CODE,ResultResponse.SUCCESS_DESC,ordersList);
    }

    @Override
    public ResultResponse cancelAppointment(Integer orderId) {
        ordersMapper.deleteByPrimaryKey(orderId);
        //给手机发送短信通知一下
       // sendMessage.sendMessage("13826189266","1234");
        return new ResultResponse(ResultResponse.SUCCESS_CODE,ResultResponse.SUCCESS_DESC,null);
    }

    /**
     * 检查医院某天有没有余号
     * 有：返回true
     * 没有：返回false
     */
    public Boolean haveRemainderNumber(Orders orders){ //2025-09-02  周二
        Boolean result=false;
        //1.获取医院的当天的总号数               -已经预约的号数=余号数量
        //先获取rule
      Hospital hospital=hospitalMapper.selectByPrimaryKey(orders.getHpId());
      String rule=hospital.getRule(); //"0,200,200,200,200,200,100"=>[0,200,200,200,200,200,100]
        //根据orderDate获取当天的总号数
        // date---周几  数字，1=周一，7=周日
       int dayOfWeek=getWeekDayNumber(orders.getOrderDate());
       int totalNumber=Integer.parseInt(rule.split(",")[dayOfWeek]); //索引是2 取数组中索引是2的值  200

        //2.已经预约的号数
        int appointmentNumber=ordersMapper.selectAlreadyAppointmentNumber(orders);

        //3.余号数量
        int remainderNumber=totalNumber-appointmentNumber;

        return remainderNumber>0?true:false;
    }

    /**
     * 获取日期的星期几（数字，1=周一，7=周日）
     */
    public static int getWeekDayNumber(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        // 转换为中国习惯：1=周一，7=周日
        return dayOfWeek == 1 ? 7 : dayOfWeek - 1;
    }


}
